package com.acme.service.bank;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import com.acme.domain.account.AbstractAccount;
import com.acme.domain.account.Account;
import com.acme.domain.account.CheckingAccount;
import com.acme.domain.account.SavingAccount;
import com.acme.domain.bank.Bank;
import com.acme.domain.bank.Client;
import com.acme.domain.bank.Gender;
import com.acme.exceptions.ClientExistsException;


public class BankDataLoader {
	private BankService bankService;


	/**
	 * Loads a file which contains data feed in the following format: <br>
	 * accounttype=c|s;balance=100;overdraft=50;name=John;gender=m|f;
	 * 
	 * @param bank
	 * @param path
	 * @throws FileNotFoundException
	 */
	public void load(final Bank bank, final String path)
            throws IOException {
        HashMap<String, String> data = new HashMap<String, String>();
        BufferedReader bin = new BufferedReader(new FileReader(path));
        String str = bin.readLine();
        bin.close();
        StringTokenizer st = new StringTokenizer(str, "=;");
        while(st.hasMoreTokens()){
            String key = st.nextToken();
            data.put(key, st.nextToken());
        }
        createFromMap(bank, data);
	}

    private void createFromMap(final Bank bank, final Map<String,String> data)  {
        Gender gender;
        Account acc;
        Client client;
        if (data.get("gender")=="m"){
            gender = Gender.MALE;
        }
        else{
            gender = Gender.FEMALE;
        }

        try{
            client = bankService.addClient(bank, data.get("name"), gender);

        } catch (ClientExistsException e) {
            e.printStackTrace();
            return;
        }
        
//        TODO: [VY] Please, move those key to final static field.
        if (data.get("accounttype")=="c"){
            acc = new CheckingAccount(AbstractAccount.getUniqueAccountNumber(),
                                      Double.parseDouble(data.get("balance")),Double.parseDouble(data.get("overdraft")));
        }
        else{
            acc = new SavingAccount(AbstractAccount.getUniqueAccountNumber(),
                    Double.parseDouble(data.get("balance")));
        }
        client.addAccount(acc);
    }


    public BankService getBankService() {
		return bankService;
	}

	public void setBankService(final BankService bankService) {
		this.bankService = bankService;
	}
}
